package com.math.aistudykbr.interceptor;

import com.math.aistudykbr.utils.JwtUtil;
import com.math.aistudykbr.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    /**
     * 进入请求前拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的用户信息
        String token = request.getHeader("token");
//        log.info("获取token：{}", token);

        // 放行预检请求，用于建立SSE连接
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        }

        // 2.判断是否为空
        if (!token.isEmpty()) {
            // 校验
            jwtUtil.validateToken(token);
            // 设置上下文
            UserContext.setUser(jwtUtil.extractUserId(token));
            log.info("设置用户上下文：userID={}", UserContext.getUser());
        }

        // 放行预检请求，用于建立SSE连接
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        }

        // 3.放行
        return true;
    }

    /**
     * 请求处理之后拦截，用于清理上下文/释放资源
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清除上下文
        UserContext.remove();
        log.info("清除用户上下文：{}", UserContext.getUser());
    }
}
